import { defineStore } from 'pinia'
import { useStudentsStore } from './students'
import { useSocketStore } from './socket'

// 异常检查管理store
export const useExceptionsStore = defineStore('exceptions', {
  state: () => ({
    // 异常列表
    exceptions: [],
    // 异常类型统计
    exceptionStats: {
      arrivalOverdue: 0 // 超过入园时间未到
    },
    // 异常检查规则配置
    checkRules: {
      // 入园时间阈值（分钟）- 超过此时间未到视为异常
      arrivalTimeThreshold: 30,
      // 是否启用实时异常检查
      enableRealTimeCheck: true
    },
    // 异常检查定时器
    checkTimer: null,
    // 检查间隔（毫秒）
    checkInterval: 10000, // 10秒
    // 异常通知列表
    notifications: [],
    // 加载状态
    loading: false,
    // 错误信息
    error: null
  }),

  getters: {
    // 获取指定类型的异常
    getExceptionsByType: (state) => (type) => {
      return state.exceptions.filter(exception => exception.type === type)
    },
    
    // 获取高优先级异常（需要立即处理）
    getHighPriorityExceptions: (state) => {
      return state.exceptions.filter(exception => 
        exception.priority === 'high' && !exception.resolved
      )
    },
    
    // 获取未解决的异常
    getUnresolvedExceptions: (state) => {
      return state.exceptions.filter(exception => !exception.resolved)
    },
    
    // 获取今日异常总数
    getTodayExceptionCount: (state) => {
      const today = new Date().toISOString().split('T')[0]
      return state.exceptions.filter(exception => 
        exception.date === today && !exception.resolved
      ).length
    },
    
    // 获取班级异常统计
    getClassExceptionStats: (state) => {
      const classStats = new Map()
      
      state.exceptions.forEach(exception => {
        if (!exception.resolved) {
          const classId = exception.class_id
          if (!classStats.has(classId)) {
            classStats.set(classId, {
              class_id: classId,
              class_name: exception.class_name,
              count: 0,
              types: new Set()
            })
          }
          
          const stats = classStats.get(classId)
          stats.count++
          stats.types.add(exception.type)
        }
      })
      
      return Array.from(classStats.values()).map(stats => ({
        ...stats,
        types: Array.from(stats.types)
      }))
    }
  },

  actions: {
    // 初始化WebSocket监听
    initSocketListeners() {
      const socketStore = useSocketStore()
      
      // 监听异常解决结果
      socketStore.on('exception-resolve-result', this.handleExceptionResolveResult)
      
      // 监听批量异常解决结果
      socketStore.on('batch-exception-resolve-result', this.handleBatchExceptionResolveResult)
    },
    
    // 处理异常解决结果
    handleExceptionResolveResult(data) {
      console.log('收到异常解决结果:', data)
      if (data.success) {
        // 更新本地状态
        const exceptionIndex = this.exceptions.findIndex(e => e.id === data.exceptionId)
        if (exceptionIndex !== -1) {
          this.exceptions[exceptionIndex].resolved = true
          this.exceptions[exceptionIndex].resolved_by = data.resolvedBy
          this.exceptions[exceptionIndex].resolved_at = new Date().toISOString()
          this.exceptions[exceptionIndex].resolution_notes = data.notes
        }
        this.updateExceptionStats()
      } else {
        this.error = data.message || '解决异常失败'
      }
    },
    
    // 处理批量异常解决结果
    handleBatchExceptionResolveResult(data) {
      console.log('收到批量异常解决结果:', data)
      if (data.success) {
        // 更新本地状态
        data.exceptionIds.forEach(id => {
          const exceptionIndex = this.exceptions.findIndex(e => e.id === id)
          if (exceptionIndex !== -1) {
            this.exceptions[exceptionIndex].resolved = true
            this.exceptions[exceptionIndex].resolved_by = data.resolvedBy
            this.exceptions[exceptionIndex].resolved_at = new Date().toISOString()
            this.exceptions[exceptionIndex].resolution_notes = data.notes
          }
        })
        this.updateExceptionStats()
      } else {
        this.error = data.message || '批量解决异常失败'
      }
    },
    
    // 执行异常检查
    async performExceptionCheck(date = null) {
      this.loading = true
      this.error = null
      
      try {
        const studentsStore = useStudentsStore()
        const targetDate = date || studentsStore.selectedDate
        
        // 获取最新的学生数据
        await studentsStore.fetchStudentsWithAttendance(targetDate)
        
        // 清空当前异常列表
        this.exceptions = []
        
        // 执行异常检查 - 只检查超过入园时间未到的异常
        this.checkArrivalOverdueExceptions(studentsStore.students, targetDate)
        
        // 更新异常统计
        this.updateExceptionStats()
        
        // 生成异常通知
        this.generateNotifications()
        
        return this.exceptions
      } catch (error) {
        this.error = error.message || '异常检查失败'
        console.error('异常检查失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 检查超过入园时间未到的异常
    checkArrivalOverdueExceptions(students, date) {
      const now = new Date()
      const thresholdTime = new Date()
      thresholdTime.setHours(8, this.checkRules.arrivalTimeThreshold, 0, 0) // 假设8:00为正常入园时间起点
      
      // 只在当前时间超过阈值时间后才检查
      if (now < thresholdTime) {
        return
      }
      
      const overdueStudents = students.filter(student => 
        student.arrival_status !== 'arrived' && 
        student.arrival_status !== 'leave' // 排除请假学生
      )
      
      overdueStudents.forEach(student => {
        // 根据校车状态确定备注信息
        let notes = ''
        if (student.bus_status === 'on_bus') {
          notes = '乘坐校车但未到'
        } else {
          notes = '未知异常'
        }
        
        this.addException({
          type: 'arrivalOverdue',
          student_id: student.id,
          student_name: student.name,
          student_number: student.student_number,
          class_id: student.class_id,
          class_name: student.class_name,
          teacher_name: student.teacher_name,
          message: `学生 ${student.name}(${student.student_number}) 超过入园时间未到`,
          priority: 'high',
          date: date,
          timestamp: new Date().toISOString(),
          notes: notes,
          details: {
            bus_status: student.bus_status,
            arrival_status: student.arrival_status,
            threshold_time: thresholdTime.toTimeString().split(' ')[0]
          }
        })
      })
    },
    

    
    // 添加异常记录
    addException(exception) {
      // 检查是否已存在相同异常
      const existingException = this.exceptions.find(e => 
        e.student_id === exception.student_id && 
        e.type === exception.type && 
        e.date === exception.date
      )
      
      if (!existingException) {
        this.exceptions.push({
          id: Date.now() + Math.random(), // 临时ID
          resolved: false,
          resolved_by: null,
          resolved_at: null,
          ...exception
        })
      }
    },
    
    // 解决异常 - 使用WebSocket
    resolveException(exceptionId, resolvedBy, notes = '') {
      const socketStore = useSocketStore()
      socketStore.emit('resolve-exception', {
        exceptionId,
        resolvedBy,
        notes
      })
    },
    
    // 批量解决异常 - 使用WebSocket
    batchResolveExceptions(exceptionIds, resolvedBy, notes = '') {
      const socketStore = useSocketStore()
      socketStore.emit('batch-resolve-exceptions', {
        exceptionIds,
        resolvedBy,
        notes
      })
    },
    
    // 更新异常统计
    updateExceptionStats() {
      this.exceptionStats.arrivalOverdue = this.getExceptionsByType('arrivalOverdue').filter(e => !e.resolved).length
    },
    
    // 生成异常通知
    generateNotifications() {
      const highPriorityExceptions = this.getHighPriorityExceptions
      
      // 清空旧通知
      this.notifications = []
      
      // 为高优先级异常生成通知
      highPriorityExceptions.forEach(exception => {
        this.notifications.push({
          id: `notification_${exception.id}`,
          type: 'warning',
          title: '异常警告',
          message: exception.message,
          timestamp: exception.timestamp,
          exception_id: exception.id,
          read: false
        })
      })
    },
    
    // 标记通知为已读
    markNotificationAsRead(notificationId) {
      const notification = this.notifications.find(n => n.id === notificationId)
      if (notification) {
        notification.read = true
      }
    },
    
    // 清除所有通知
    clearAllNotifications() {
      this.notifications = []
    },
    
    // 开始实时异常检查
    startRealTimeCheck() {
      if (!this.checkRules.enableRealTimeCheck) return
      
      if (this.checkTimer) {
        clearInterval(this.checkTimer)
      }
      
      this.checkTimer = setInterval(() => {
        this.performExceptionCheck()
      }, this.checkInterval)
    },
    
    // 停止实时异常检查
    stopRealTimeCheck() {
      if (this.checkTimer) {
        clearInterval(this.checkTimer)
        this.checkTimer = null
      }
    },
    
    // 更新检查规则
    updateCheckRules(newRules) {
      this.checkRules = { ...this.checkRules, ...newRules }
      
      // 如果实时检查被禁用，停止定时器
      if (!this.checkRules.enableRealTimeCheck) {
        this.stopRealTimeCheck()
      }
    },
    
    // 设置检查间隔
    setCheckInterval(interval) {
      this.checkInterval = interval
      if (this.checkTimer) {
        this.stopRealTimeCheck()
        this.startRealTimeCheck()
      }
    },
    
    // 清除错误
    clearError() {
      this.error = null
    },
    
    // 重置store状态
    resetStore() {
      this.exceptions = []
      this.exceptionStats = {
        arrivalOverdue: 0
      }
      this.notifications = []
      this.loading = false
      this.error = null
      this.stopRealTimeCheck()
    }
  }
})